package com.mt.mtbletools;

import java.util.ArrayList;
import java.util.List;

import com.mt.mtbletools.R;
import com.mt.sdk.tools.MTTools;
import com.mt.view.TalkMsgView;

import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class TalkFragment extends Fragment {

	private Context context;
	public TalkFragment(Context context) {
		this.context = context;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	private View view;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		if (view != null) {
			return view;
		}

		view = inflater.inflate(R.layout.fragment_talk, container, false);

		initView();

		return view;
	}

	// 初始化控件
	private ListView chat_list;
	private List<TalkFragment.Msg> chats = new ArrayList<TalkFragment.Msg>();
	private Button send_btn;
	private EditText senddatas_s_edit;
	private EditText senddatas_16_edit;
	private Spinner read_fmt_select;
	private TextView conect_flag_btn;
	private Button clear_btn;

	private LinearLayout senddata_layout;
	private CheckBox sendontime_check;
	private EditText sendontime_edit;
	private Spinner write_fmt_select;
	private LinearLayout recivedata_layout;
	private TextView recivedatauuid_txt;
	private TextView recivedata_txt;
	private Button dismiss_btn;
	private Button read_btn;
	
	private void initView() {
		chat_list = (ListView) view.findViewById(R.id.chat_list);
		send_btn = (Button) view.findViewById(R.id.send_btn);

		senddatas_s_edit = (EditText) view.findViewById(R.id.senddatas_s_edit);
		senddatas_16_edit = (EditText) view.findViewById(R.id.senddatas_16_edit);

		read_fmt_select = (Spinner) view.findViewById(R.id.read_fmt_select);
		conect_flag_btn = (TextView) view.findViewById(R.id.conect_flag_btn);
		clear_btn = (Button) view.findViewById(R.id.clear_btn);

		sendontime_check = (CheckBox) view.findViewById(R.id.sendontime_check);
		sendontime_edit = (EditText) view.findViewById(R.id.sendontime_edit);
		write_fmt_select = (Spinner) view.findViewById(R.id.write_fmt_select);

		recivedata_layout = (LinearLayout) view.findViewById(R.id.recivedata_layout);
		recivedatauuid_txt = (TextView) view.findViewById(R.id.recivedatauuid_txt);
		recivedata_txt = (TextView) view.findViewById(R.id.recivedata_txt);
		dismiss_btn = (Button) view.findViewById(R.id.dismiss_btn);
		read_btn = (Button) view.findViewById(R.id.read_btn);
		senddata_layout = (LinearLayout) view.findViewById(R.id.senddata_layout);

		chat_list.setAdapter(chatlistAdapter);

		send_btn.setOnClickListener(myOnClickListener);
		clear_btn.setOnClickListener(myOnClickListener);
		sendontime_check.setOnClickListener(myOnClickListener);
		dismiss_btn.setOnClickListener(myOnClickListener);
		read_btn.setOnClickListener(myOnClickListener);

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.datafmts,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		read_fmt_select.setAdapter(adapter);
		write_fmt_select.setAdapter(adapter);

		write_fmt_select.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				senddatas_s_edit.setVisibility(View.GONE);
				senddatas_16_edit.setVisibility(View.GONE);
				switch (write_fmt_select.getSelectedItemPosition()) {
				case 0:
					senddatas_s_edit.setVisibility(View.VISIBLE);
					senddatas_s_edit.setFocusable(true); // 获取输入焦点
					senddatas_s_edit.setFocusableInTouchMode(true);
					senddatas_s_edit.requestFocus();
					break; // 字符串
				case 1:
					senddatas_16_edit.setVisibility(View.VISIBLE);
					senddatas_16_edit.setFocusable(true); // 获取输入焦点
					senddatas_16_edit.setFocusableInTouchMode(true);
					senddatas_16_edit.requestFocus();
					break; // 16进制
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});

		reflashAllDatas();
		
		setProperty(writeable, readable);
		setConnectStatues(connectStatues);
	}

	// 按钮监听
	private OnClickListener myOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (v == send_btn) {
				Msg msg = getSendMsg();
				chats.add(msg);
				onSendMsg(msg);
				chatlistAdapter.notifyDataSetChanged();
				return;
			}

			if (v == clear_btn) {
				chats.clear();
				chatlistAdapter.notifyDataSetChanged();
				return;
			}

			if (v == sendontime_check) {
				if (sendontime_check.isChecked()) {
					handl.sendEmptyMessage(SENDONTIME);
				}
				return;
			}
			
			if(v == dismiss_btn){
				recivedata_layout.setVisibility(View.GONE);
				return;
			}
			
			if(v == read_btn){
				onRead();
				return;
			}
		}
	};

	// 发送数据回调
	protected void onSendMsg(Msg msg) {

	}
	
	// 读取数据回调
	protected void onRead() {
		
	}
	
	// 设置权限
	private boolean writeable = false;
	private boolean readable = false;
	public void setProperty(boolean writeable, boolean readable){
		this.writeable = writeable;
		this.readable  = readable;
		if(chat_list == null){
			return;
		}
		
		if(this.writeable){
			senddata_layout.setVisibility(View.VISIBLE);
		}else{
			senddata_layout.setVisibility(View.GONE);
		}
		
		if(this.readable){
			read_btn.setVisibility(View.VISIBLE);
		}else{
			read_btn.setVisibility(View.GONE);
		}
	}

	// 设置连接状态
	private boolean connectStatues = true;

	public void setConnectStatues(boolean statues) {
		this.connectStatues = statues;
		if(conect_flag_btn == null){
			return;
		}
		if (connectStatues) {
			conect_flag_btn.setText(context.getResources().getString(R.string.connected));
		} else {
			conect_flag_btn.setText(context.getResources().getString(R.string.disconnect));
		}
	}

	// 刷新全部控件状态
	private void reflashAllDatas() {
		// 显示控制状态
		setConnectStatues(connectStatues);
	}

	// 获取要发送的数据
	private Msg getSendMsg() {
		Msg msg = new Msg();
		msg.setDir(Msg.DIR.SEND);
		if (write_fmt_select.getSelectedItemPosition() == 0) { // 字符串状态
			msg.setRealmsg(senddatas_s_edit.getText().toString().getBytes());
			msg.setDismsg(senddatas_s_edit.getText().toString());
		} else if (write_fmt_select.getSelectedItemPosition() == 1) { // 16进制状态
			byte[] realdatas = MTTools.convertStringToByteArray(senddatas_16_edit.getText().toString());
			msg.setRealmsg(realdatas);
			msg.setDismsg(senddatas_16_edit.getText().toString());
		}

		return msg;
	}

	// 列表适配器
	private BaseAdapter chatlistAdapter = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = new TalkMsgView(getContext());
			}

			((TalkMsgView) convertView).setDatas(getItem(position));

			return convertView;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public TalkFragment.Msg getItem(int position) {
			return chats.get(position);
		}

		@Override
		public int getCount() {
			return chats.size();
		}
	};

	// 接收自身数据
	public void receiveSelfdata(Msg msg) {

		if(read_fmt_select == null){
			return;
		}
		if (read_fmt_select.getSelectedItemPosition() == 0) { // 字符串显示
			msg.setDismsg(new String(msg.getRealmsg()));
		} else {
			msg.setDismsg(MTTools.convertBytearrayToString(msg.getRealmsg()));
		}

		chats.add(msg);
		handl.post(new Runnable() {

			@Override
			public void run() {
				chatlistAdapter.notifyDataSetChanged();
			}
		});
	}

	// 接收别人数据
	public void reciveOtherdata(Msg msg) {
		if(recivedata_layout == null){
			return;
		}
		recivedata_layout.setVisibility(View.VISIBLE);
		recivedatauuid_txt.setText(context.getResources().getString(R.string.uuid) + msg.getCharact().getUuid().toString());
		recivedata_txt.setText(context.getResources().getString(R.string.datas) + msg.getDismsg());
	}

	// 设置数据记录
	public void setHisDatas(List<TalkFragment.Msg> chats){
		this.chats = chats;
		if(recivedata_layout != null){
			recivedata_layout.setVisibility(View.GONE);
		}
	}
	
	// 信息包
	public static class Msg {
		private byte[] realmsg; // 实际数据
		private String dismsg; // 显示数据
		private BluetoothGattCharacteristic charact; // 对应特征值
		private DIR dir = DIR.SEND;

		public Msg() {
		}

		public Msg(BluetoothGattCharacteristic charact, DIR dir, byte[] realmsg, String dismsg) {
			this.charact = charact;
			this.dir = dir;
			this.realmsg = realmsg;
			this.dismsg = dismsg;
		}

		public byte[] getRealmsg() {
			return realmsg;
		}

		public void setRealmsg(byte[] realmsg) {
			this.realmsg = realmsg;
		}

		public String getDismsg() {
			return dismsg;
		}

		public void setDismsg(String dismsg) {
			this.dismsg = dismsg;
		}

		public BluetoothGattCharacteristic getCharact() {
			return charact;
		}

		public void setCharact(BluetoothGattCharacteristic charact) {
			this.charact = charact;
		}

		public DIR getDir() {
			return dir;
		}

		public void setDir(DIR dir) {
			this.dir = dir;
		}

		// 发送方向
		public enum DIR {
			SEND, RECIVE
		}
	}

	// 定时发送数据
	private final int SENDONTIME = 4;
	private Handler handl = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if (!sendontime_check.isChecked()) {
				return;
			}
			if (sendontime_edit.getText().toString().length() == 0) {
				sendontime_check.setChecked(false);
				return;
			}

			Msg sendmsg = getSendMsg();
			onSendMsg(sendmsg);

			int deleytime = Integer.parseInt(sendontime_edit.getText().toString());
			handl.sendEmptyMessageDelayed(SENDONTIME, deleytime);
		}
	};

	@Override
	public void onPause() {
		super.onPause();
		sendontime_check.setChecked(false);
		recivedata_layout.setVisibility(View.GONE);
		handl.removeMessages(SENDONTIME);
	};
}
